package com.zhkjnet.zhyy.controller;

import com.zhkjnet.zhyy.bean.JsonResponse;
import com.zhkjnet.zhyy.bean.RequiredPermission;
import com.zhkjnet.zhyy.bean.Roles;
import com.zhkjnet.zhyy.bean.UserAsset;
import com.zhkjnet.zhyy.entity.*;
import com.zhkjnet.zhyy.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.Map;

@RestController
@RequestMapping("/api")
public class ApiController {

    @Autowired
    private UserService userService;

    @Autowired
    private OilCardService oilCardService;

    @Autowired
    private AdminService adminService;

    @Autowired
    private RechargeRecordService rechargeRecordService;

    @Autowired
    private AssetService assetService;

    @Autowired
    private OilRechargeService oilRechargeService;

    @Autowired
    private MoneyRecordService moneyRecordService;

    @Autowired
    private HttpSession session;

    /**
     * 新建用户
     * @param userAsset  包含用户和bean的
     * @return
     */
    @RequiredPermission(Roles.Admin)
    @PostMapping("/users")
    public JsonResponse saveUser(@RequestBody UserAsset userAsset) {
        userService.save(userAsset.getUser(), userAsset.getAsset().getMinMoney());
        return JsonResponse.success(userAsset.getUser().getId());
    }

    /**
     * 删除用户
     * @param id
     * @return
     */
    @RequiredPermission(Roles.Admin)
    @DeleteMapping("/users/{id}")
    public JsonResponse deleteUser(@PathVariable("id") Long id) {
        userService.deleteById(id);
        return JsonResponse.success();
    }

    /**
     * 新建管理员
     * @param admin
     * @return
     */
    @RequiredPermission(Roles.Admin)
    @PostMapping("/admins")
    public JsonResponse saveAdmin(@RequestBody Admin admin) {
        adminService.save(admin);
        return JsonResponse.success(admin.getId());
    }

    /**
     * 删除管理员
     * @param id
     * @return
     */
    @RequiredPermission(Roles.Admin)
    @DeleteMapping("/admins/{id}")
    public JsonResponse deleteAdmin(@PathVariable("id") Long id) {
        adminService.deleteById(id);
        return JsonResponse.success();
    }

    /**
     * 新建油卡
     * @param oilCard
     * @return
     */
    @RequiredPermission(Roles.User)
    @PostMapping("/oilCards")
    public JsonResponse saveOilCard(@RequestBody OilCard oilCard) {
        Long userId = (Long) session.getAttribute("id");
        User user = new User();
        user.setId(userId);
        oilCardService.save(oilCard, user);
        return JsonResponse.success(oilCard.getId());
    }

    /**
     * 删除油卡
     * @param id  油卡id
     * @return
     */
    @RequiredPermission(Roles.User)
    @DeleteMapping("/oilCards/{id}")
    public JsonResponse deleteOilCard(@PathVariable("id") Long id) {
        oilCardService.deleteById(id);
        return JsonResponse.success();
    }

    /**
     * 管理员登陆
     * @return
     */
    @PostMapping("/admin/login")
    public JsonResponse adminLogin(@RequestBody Admin admin) {
        Admin result = adminService.findByPhoneAndPassword(admin.getPhone(), admin.getPassword());
        if (result != null) {
            session.setAttribute("role", Roles.Admin);
            session.setAttribute("id", result.getId());
            return JsonResponse.success();
        } else {
            return JsonResponse.error(1, "手机号码或密码错误");
        }
    }

    /**
     * 用户登录
     * @return
     */
    @PostMapping("/user/login")
    public JsonResponse userLogin(@RequestBody User user) {
        User result = userService.findByPhoneAndPassword(user.getPhone(), user.getPassword());
        if (result != null) {
            session.setAttribute("role", Roles.User);
            session.setAttribute("id", result.getId());
            return JsonResponse.success();
        } else {
            return JsonResponse.error(1, "手机号码或密码错误");
        }
    }

    /**
     * 充值
     * @param record
     * @return
     */
    @RequiredPermission(Roles.User)
    @PostMapping("/rechargeRecords")
    public JsonResponse saveRechargeRecord(@RequestBody RechargeRecord record) {
        Long userId = (Long) session.getAttribute("id");
        Long min = assetService.findMinRechargeMoneyByUserId(userId);
        if (record.getMoney() < min) {
            return JsonResponse.error(1, "不能小于最小充值金额");
        }
        User user = new User();
        user.setId(userId);
        record.setUser(user);
        rechargeRecordService.save(record);
        return JsonResponse.success();
    }


    /**
     * 充值进余额
     * @return
     */
    @RequiredPermission(Roles.Admin)
    @PutMapping("/recharges/{id}/{status}")
    public JsonResponse recharge(@PathVariable("id") Long id, @PathVariable("status") RechargeStatus status) {
        Long userId = (Long) session.getAttribute("id");
        User transactor = new User();
        transactor.setId(userId);
        if (status == RechargeStatus.Success) {
            assetService.rechargeById(id, transactor);
        } else if (status == RechargeStatus.Fail) {
            RechargeRecord record = new RechargeRecord();
            record.setId(id);
            record.setTransactor(transactor);
            record.setTransactTime(new Date());
            record.setStatus(RechargeStatus.Fail);
            rechargeRecordService.update(record);
        }
        return JsonResponse.success();
    }

    /**
     * 油卡充值
     * @param oilRecharge
     * @return
     */
    @RequiredPermission(Roles.User)
    @PostMapping("/oilRecharges")
    public JsonResponse oilRecharge(@RequestBody OilRecharge oilRecharge) {
        Long userId = (Long) session.getAttribute("id");
        User user = new User();
        user.setId(userId);
        Asset asset = assetService.findByUserId(userId);
        if (asset.getAbleMoney() < oilRecharge.getMoney()) {
            return JsonResponse.error(1, "可用余额不足");
        }
        boolean result = oilRechargeService.save(oilRecharge, asset, user);
        if (result) {
            return JsonResponse.success("充值成功");
        } else {
            return JsonResponse.error(1, "充值接口调用失败");
        }
    }

    /**
     * 查询所有记录
     * @param page
     * @return
     */
    @RequiredPermission(Roles.User)
    @GetMapping("/user/oilRecharges")
    public JsonResponse oilRecharges(@RequestParam Long page) {
        Long userId = (Long) session.getAttribute("id");
        Integer length = 20;
        return JsonResponse.success(oilRechargeService.findAllByUserId(userId, (page - 1) * length, length));
    }

    /**
     * 查询当前用户所有资金情况
     * @param page
     * @return
     */
    @RequiredPermission(Roles.User)
    @GetMapping("/user/moneyRecords")
    public JsonResponse userMoneyRecords(@RequestParam Long page) {
        Long userId = (Long) session.getAttribute("id");
        Integer length = 20;
        return JsonResponse.success(moneyRecordService.findAllByUserId(userId, null, page, length));
    }


    /**
     * 修改密码
     * @param map
     * @return
     */
    @RequiredPermission(Roles.User)
    @PutMapping("/user/password")
    public JsonResponse updateUserPassword(@RequestBody Map<String, String> map) {
        Long userId = (Long) session.getAttribute("id");
        String password = map.get("password");
        userService.updatePassword(userId, password);
        return JsonResponse.success();
    }

    /**
     * 批量充油
     * @param requeset
     * @param response
     * @param gasType
     * @param cards
     * @param prices
     * @return
     */
    @RequiredPermission(Roles.User)
    @PostMapping("/user/oilRechargeBatch")
    public JsonResponse oilRechargeBatch(HttpServletRequest request,HttpServletResponse response,String cardType,String cards,Long prices){
    	
    	JsonResponse json = oilRechargeService.oilRechargeBatch(request,response,cardType,cards,prices);
    	
		return json;
    	
    }
    
    
}
